//
//  VOLAllCommentViewController.m
//  Volver
//
//  Created by administrator on 14-10-27.
//  Copyright (c) 2014年 vol. All rights reserved.
//

#import "VOLAllCommentViewController.h"

#import "common.h"
#import "HTTPDefine.h"

#import "ASIHTTPRequest.h"
#import "JSONKit.h"
#import "MJRefresh.h"

#import "VOLAppDelegate.h"
#import "VOLCommentCell.h"
#import "VOLCommentCellModel.h"
#import "NSString+ext.h"

@interface VOLAllCommentViewController ()
{
    JSONDecoder *jd;
    VOLAppDelegate *del;
    NSFileManager *manager;
    NSDateFormatter *formatter;
    
    UITableViewCell *propertyCell;
    
    //数据源数组
    NSMutableArray *commentData;
}
@end

@implementation VOLAllCommentViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    //初始化一些对象
    del = kGetDel;
    jd = [[JSONDecoder alloc] init];
    manager = [NSFileManager defaultManager];
    
    commentData = [NSMutableArray array];
    
    propertyCell = [self.tableView dequeueReusableCellWithIdentifier:@"commentCell"];
    //设置标题，放在后面，显示评论的数量
    self.title = @"所有评论";
    //添加返回按钮
    addBackButton();
    
    //隐藏noticeLabel
    self.noticeLabel.hidden = YES;
    
    //加载数据
    [self loadAllCommentByHouseID:self.houseID];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 按钮点击事件
#pragma mark 返回
-(void)goBack:(id)sender{
    back;
}


#pragma mark - 其它方法



#pragma mark - 加载数据方法
-(void)loadAllCommentByHouseID:(int)houseID{
    //采用异步方式
    
    //发送异步请求
    NSString *urlstr = [NSString stringWithFormat:@"%@comment/searchCommentsByHouseID?houseID=%d",kHTTPHome,houseID];
    NSURL *url = [NSURL URLWithString:urlstr];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    //设置代理
    request.delegate = self;
    [request startAsynchronous];
}




#pragma mark - 代理方法

#pragma mark 异步请求代理方法
#pragma mark 请求完成的方法：
-(void)requestFinished:(ASIHTTPRequest *)request{
    //得到返回数据
    NSData *data = [request responseData];
    
    if (data == nil) {
        NSLog(@"allComment------data为空");
        return;
    }
    
    NSDictionary *dic = [jd objectWithData:data];
    
    int status = [[dic objectForKey:@"status"] intValue];
    if (status == 0) {
        NSLog(@"allComment------没有评论");
    }else{
        //得到房屋数组
        NSArray *commentArray = [dic objectForKey:@"comment"];
        
        //遍历这个数组，将内容取出
        for (NSDictionary *obj in commentArray) {
            VOLCommentCellModel *model = [[VOLCommentCellModel alloc] init];
            model.userID = [[obj objectForKey:@"user_id"] intValue];
            model.userHeadImageName = [obj objectForKey:@"user_head"];
            model.userName = [obj objectForKey:@"user_name"];
            model.content = [obj objectForKey:@"c_content"];
            model.score = [[obj objectForKey:@"c_score"] intValue];
            model.commentTime = [[obj objectForKey:@"c_time"] doubleValue];
            
            //添加到favoriteHouses中
            [commentData addObject:model];
        }
    }
    
    
    
    //遍历完成后，返回主线程更新界面
    //判断是否有收藏的房屋
    if (commentData.count == 0) {
        //显示提示Label
        self.noticeLabel.text = @"这个房子还没有评论~~";
        self.noticeLabel.textColor = kThemeColor;
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.noticeLabel.hidden = NO;
    }else{
        //初始化formatter
        formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy.MM.dd  HH:mm:ss"];
        //设置标题
        self.title = [NSString stringWithFormat:@"所有评论（%d）",commentData.count];
        self.noticeLabel.hidden = YES;
    }
    
    //刷新tableView
    [self.tableView reloadData];
    
}

#pragma mark 请求失败的方法：
-(void)requestFailed:(ASIHTTPRequest *)request{
    //停止刷新动作
    [self.tableView headerEndRefreshing];
    NSLog(@"favorite-----请求失败");
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return commentData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"commentCell";
    VOLCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    // Configure the cell...
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.commentTimeLabel.textColor = kPriceLabelColor;
    cell.scoreLabel.textColor = kOrangeColor;
    cell.userHeadImageView.layer.masksToBounds = YES;
    cell.userHeadImageView.layer.cornerRadius = 25.0;
    cell.userHeadImageView.layer.borderColor = [UIColor whiteColor].CGColor;
    cell.userHeadImageView.layer.borderWidth = 1.0f;
    cell.userHeadImageView.layer.rasterizationScale = [UIScreen mainScreen].scale;
    cell.userHeadImageView.layer.shouldRasterize = YES;
    cell.userHeadImageView.clipsToBounds = YES;
    
    VOLCommentCellModel *model = commentData[indexPath.row];
    cell.userNameLabel.text = model.userName;
    cell.commentTimeLabel.text = [formatter stringFromDate:kTransformToDate(model.commentTime)];
    cell.contentLabel.text = model.content;
    cell.scoreLabel.text = [NSString stringWithFormat:@"%d分",model.score];

    //求出text的高度
    CGSize size = [model.content calculateSize:CGSizeMake(cell.contentLabel.frame.size.width, FLT_MAX) font:cell.contentLabel.font];
    //设置label的frmae
    cell.contentLabel.frame = CGRectMake(cell.contentLabel.frame.origin.x, cell.contentLabel.frame.origin.y, size.width, size.height );
    
    //加载头像
    if ((NSNull *)model.userHeadImageName != [NSNull null]) {
        //加载图片
        //先判断是否有这个路径存在，如果没有要先创建
        NSString *imageDocumentPath = [NSString stringWithFormat:@"%@%d/userHead/%d",kGetDocumentsPath,del.currentUser.userID,model.userID];
        if (![manager fileExistsAtPath:imageDocumentPath]) {
            [manager createDirectoryAtPath:imageDocumentPath withIntermediateDirectories:YES attributes:nil error:nil];
        }
        //先从本地查找是否已有图片
        NSString *imagePath = [NSString stringWithFormat:@"%@%d/userHead/%d/%@",kGetDocumentsPath,del.currentUser.userID,model.userID,model.userHeadImageName];
        if ([manager fileExistsAtPath:imagePath]) {
            cell.userHeadImageView.image = [UIImage imageWithContentsOfFile:imagePath];
        }
        else{
            //若不存在，调用方法下载图片
            [del loadHeadImage:model.userHeadImageName userID:model.userID headImageView:cell.userHeadImageView imagePath:imagePath];
        }
    }
    else{
        cell.userHeadImageView.image = [UIImage imageNamed:@"defaultHead.png"];
    }
    
    
    return cell;
}

#pragma mark 预设行高
-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 115;
}

#pragma mark 实际行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    //获得一个单元格
    VOLCommentCell *cell = (VOLCommentCell *)propertyCell;
    
    //当前字符串
    NSString *content = [[commentData objectAtIndex:indexPath.row] content];
    CGSize size = [content calculateSize:CGSizeMake(320, FLT_MAX) font:cell.contentLabel.font];
    //新高度
    float newHeight = size.height + 75;
    
    //返回cell的总高度
    return newHeight;
}



@end
